package cn.lingyangwl.agile.auth.controller;

import cn.hutool.core.util.StrUtil;
import cn.lingyangwl.agile.auth.service.*;
import cn.lingyangwl.agile.misc.statistic.*;
import cn.lingyangwl.agile.misc.statistic.model.*;
import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.agile.model.module.auth.*;
import cn.lingyangwl.framework.core.response.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 平台专属授权接口
 * @author shenguangyang
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthController {

	private final StatisticApi statisticApi;

	private final OAuth2TokenService tokenService;

//
//	/**
//	 * 用于授权码模式登录时候, 确认授权
//	 */
//	@GetMapping("/confirm_access")
//	public ModelAndView confirm(Principal principal, ModelAndView modelAndView,
//								@RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId,
//								@RequestParam(OAuth2ParameterNames.SCOPE) String scope,
//								@RequestParam(OAuth2ParameterNames.STATE) String state) {
//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		AuthenticatedUser authenticatedUser = (AuthenticatedUser) authentication.getPrincipal();
//		AuthClientResp clientDetails = authApi.getByClientId(clientId);
//		if (Objects.isNull(clientDetails)) {
//			throw new OAuthClientException("clientId 不合法");
//		}
//
//		Set<String> authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope());
//		modelAndView.addObject("clientId", clientId);
//		modelAndView.addObject("state", state);
//		modelAndView.addObject("scopeList", authorizedScopes);
//		modelAndView.addObject("principalName", principal.getName());
//		modelAndView.setViewName("ftl/confirm");
//		return modelAndView;
//	}

	/**
	 * 退出并删除token
	 * @param authHeader Authorization
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.DELETE })
	public Resp<Boolean> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
		if (StrUtil.isBlank(authHeader)) {
			return Resp.ok();
		}
		String tokenValue = authHeader.replace(OAuth2Cons.TokenType.BEARER, StrUtil.EMPTY).trim();

		boolean ret = tokenService.removeAccessToken(tokenValue);
		if (ret) {
			DayDimStatReq statReq = new DayDimStatReq();
			statReq.setLogoutCount(1);
			statisticApi.sendMsg(statReq);
		}

		return Resp.ok(ret);
	}

	/**
	 * 删除指定用户的访问令牌
	 */
	@DeleteMapping("/removeAccessTokenByUserId")
	public Resp<Boolean> removeAccessTokenByUserId(@RequestParam("userId") Long userId) {
		return Resp.ok(tokenService.removeAccessTokenByUserId(userId));
	}

	/**
	 * 删除指定用户的访问令牌
	 */
	@DeleteMapping("/removeAccessTokenByUserIds")
	public Resp<Boolean> removeAccessTokenByUserIds(@RequestParam("userIds") List<Long> userIds) {
		userIds.forEach(tokenService::removeAccessTokenByUserId);
		return Resp.ok(true);
	}

	/**
	 * 获取当前授权用户
	 */
	@GetMapping("/getLoginUser")
	public Resp<LoginUser> getLoginUser() {
		return Resp.ok(tokenService.getLoginUser());
	}

	/**
	 * 更新当前授权用户
	 */
	@PostMapping("/updateLocalUser")
	public Resp<Boolean> updateLoginUser(@RequestBody LoginUser loginUser) {
		tokenService.updateLoginUser(loginUser);
		return Resp.ok(true);
	}

//	/**
//	 * 校验token
//	 * @param token 令牌
//	 */
//	@SneakyThrows
//	@GetMapping("/check_token")
//	public void checkToken(String token, HttpServletResponse response, HttpServletRequest request) {
//		try (ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response)) {
//
//			if (StrUtil.isBlank(token)) {
//				httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
//				this.authenticationFailureHandler.onAuthenticationFailure(request, response,
//						new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING));
//			}
//			OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
//
//			// 如果令牌不存在 返回401
//			if (authorization == null || authorization.getAccessToken() == null) {
//				this.authenticationFailureHandler.onAuthenticationFailure(request, response,
//						new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN));
//			}
//
//			assert authorization != null;
//			Map<String, Object> claims = authorization.getAccessToken().getClaims();
//			OAuth2AccessTokenResponseesp.ok(sendAccessTokenResponse));
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//	}

}
